package com.ruoyi.common.utils.baidu;

import fr.opensagres.xdocreport.document.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;
import java.util.List;

/**
 * 网络图片文字识别
 */
public class GeneralBasic {

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String generalBasic(String path) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        try {
            // 本地文件路径
            String filePath = path;
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;
            String result="";
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();
            String str = HttpUtil.post(url, accessToken, param);
            //转为JSON格式
            JSONObject jsonObect = new JSONObject(str);
            //获取words_resultKEY
            List<JSONObject> list= (List<JSONObject>) jsonObect.get("words_result");
            for (int i = 0; i < list.size(); i++) {
                result+=list.get(i).get("words");
            }
            //分割字符串
            String substr=null;
            if (result.contains("途经:")){
               substr = StringUtils.substringBetween(result, "途经:", "结果包含您").replaceAll(",","");
            }
            return substr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}